<template>
  <div class="user-center-container">
    <a-row class="user-center-layout" :gutter="24" style="margin-right: 0;">
      <!-- 左侧：个人信息侧边栏 -->
      <a-col :xs="24" :sm="24" :md="8" :lg="6" :xl="5" class="sidebar-col">
        <div class="sidebar-container">
          <!-- 个人头像和基本信息 -->
          <div class="user-profile-card">
            <div class="avatar-container">
              <a-avatar :size="90" :src="user.userInfo?.avatar">
                {{ user.userInfo?.name?.substring(0, 1) || 'U' }}
              </a-avatar>
              <div class="avatar-upload">
                <a-upload :show-upload-list="false" :before-upload="beforeAvatarUpload">
                  <a-button type="primary" shape="circle" size="small">
                    <template #icon><camera-outlined /></template>
                  </a-button>
                </a-upload>
              </div>
            </div>

            <div class="user-sex">
              <!-- <bank-outlined /> -->
              <span>{{ getGenderText(user.userInfo?.sex) || '未设置性别' }}</span>
            </div>

            <h2 class="user-name">{{ user.userInfo?.name || '未设置姓名' }}</h2>
            <div class="user-tags">
              <a-tag color="blue">{{ user.userInfo?.isTeacher === 1 ? '教师' : '学生' }}</a-tag>
            </div>

            <div class="user-info-item">
              <bank-outlined />
              <span>{{ user.userInfo?.collegeName || '未设置学院' }}</span>
            </div>

            <div class="user-info-item">
              <bank-outlined />
              <span>{{ user.userInfo?.sClass || '未设置班级' }}</span>
            </div>

            <div class="user-info-item">
              <!-- <id-card-outlined /> -->
              <IdcardOutlined />
              <span>{{ user.userInfo?.number || '未设置学号' }}</span>
            </div>

            <div class="user-info-item">
              <mail-outlined />
              <span>{{ user.userInfo?.email || '未设置邮箱' }}</span>
            </div>

            <div class="user-info-item">
              <phone-outlined />
              <span>{{ user.userInfo?.phone || '未设置电话' }}</span>
            </div>

            <div class="action-buttons">
              <a-button type="primary" block @click="showEditModal">
                <template #icon><edit-outlined /></template>
                修改资料
              </a-button>
            </div>
          </div>


          <!-- 左侧底部可添加的功能区块 -->
          <div class="sidebar-stats-card">
            <h3>活动统计</h3>
            <div class="stats-row">
              <div class="stat-item">
                <trophy-outlined />
                <div class="stat-info">
                  <div class="stat-value">{{ raceCount || 0 }}</div>
                  <div class="stat-label">参与比赛</div>
                </div>
              </div>

              <div class="stat-item">
                <team-outlined />
                <div class="stat-info">
                  <div class="stat-value">{{ teamCount || 0 }}</div>
                  <div class="stat-label">指导团队</div>
                </div>
              </div>

              <div class="stat-item">
                <crown-outlined />
                <div class="stat-info">
                  <div class="stat-value">{{ awardCount || 0 }}</div>
                  <div class="stat-label">获得奖项</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-col>

      <!-- 右侧：主要内容区 -->
      <a-col :xs="24" :sm="24" :md="16" :lg="18" :xl="19" class="content-col">
        <div class="main-content">
          <!-- 我的比赛/活动区域 -->
          <a-card title="我的比赛" class="content-card competitions-card" :bordered="false">
            <template #extra>
              <a-button type="link" @click="toggleVisibility" v-if="currentAllRace.length > 2">
                查看全部
              </a-button>
            </template>

            <a-empty v-if="!currentAllRace.length" description="暂无参赛记录" />

            <div v-else class="competition-list">
              <div v-for="race in currentAllRace" :key="race.id" class="competition-item">
                <a-tag :color="getRaceStatusColor(race.status)" class="competition-status">
                  {{ getRaceStatusText(race.status) }}
                </a-tag>

                <div class="competition-info">
                  <div class="competition-name">{{ race.name }}</div>
                  <div class="competition-date">
                    <calendar-outlined /> {{ race.raceStart }} 至 {{ race.raceEnd }}
                  </div>
                </div>

                <div class="competition-actions">
                  <a-button type="primary" size="small" @click="viewRaceDetail(team)">
                    查看详情
                  </a-button>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 通知消息区域 -->
           <a-card title="通知消息" class="content-card notifications-card" :bordered="false">
            <template #extra>
              <a-button type="link" @click="viewAllNotifications">
                全部消息
              </a-button>
            </template>

            <a-empty v-if="!notifications.length" description="暂无通知消息" />

            <a-list v-else class="notification-list">
              <a-list-item v-for="item in notifications" :key="item.id" class="notification-item">
                <a-list-item-meta>
                  <template #avatar>
                    <a-avatar :style="{ backgroundColor: getNotificationColor(item.type) }">
                      <template #icon>
                        <notification-outlined v-if="item.type === 'system'" />
                        <trophy-outlined v-else-if="item.type === 'competition'" />
                        <file-outlined v-else />
                      </template>
                    </a-avatar>
                  </template>

                  <template #title>
                    <div class="notification-title">
                      {{ item.title }}
                      <a-badge v-if="item.isUnread" status="processing" />
                    </div>
                  </template>

                  <template #description>
                    <div class="notification-desc">
                      <div>{{ item.content }}</div>
                      <div class="notification-time">
                        <clock-circle-outlined /> {{ item.createTime }}
                      </div>
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </a-list>
          </a-card> 

          <!-- 团队管理区域 -->
          <a-card title="我的团队" class="content-card teams-card" :bordered="false">
            <template #extra>

              <a-button type="link" @click="MyTeamesVisibility" v-if="currentAllTeam.length > 6">
                查看全部
              </a-button>
            </template>

            <a-empty v-if="!currentAllTeam.length" description="暂无团队信息" />

            <div v-else class="teams-list">
              <div style="margin: auto;">
                <a-row :gutter="16">
                  <a-col v-for="team in currentAllTeam.slice(0, 6)" :key="team.id" :xs="24" :sm="12" :md="8" :lg="8">
                    <div class="team-card">
                      <div class="team-header">
                        <div class="team-name">{{ team.name }}</div>
                        <a-tag :color="getRaceTypeColor(team.type)">{{
                          getProjectType(team.type)
                        }}</a-tag>
                      </div>
                      <div class="team-content">
                        <p><user-outlined /> 负责人：{{ team.leaderName }}</p>
                        <p><team-outlined /> 成员数：{{ team.memberCount }}</p>
                        <p><trophy-outlined /> 参赛项目：{{ team.project }}</p>
                      </div>
                      <div class="button" style="display: flex;justify-content: space-evenly;flex-direction: row">
                        <div class="team-footer">
                          <a-button type="primary" size="small"
                            :style="{ backgroundColor: 'orange', borderColor: 'orange', color: 'black' }"
                            @click="handleRecruitClick(team)">
                            招募
                          </a-button>
                        </div>
                        <div class=" team-footer">
                          <a-button type="primary" size="small" @click="viewTeamDetail(team)">查看详情</a-button>
                        </div>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </div>
            </div>
          </a-card>
        </div>
      </a-col>
    </a-row>
  </div>

  <!-- 编辑信息模态框 -->
  <a-modal v-model:visible="editModalVisible" title="编辑个人信息" @ok="handleEditOk" width="700px" class="custom-edit-modal">
    <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical" class="custom-form">
      <a-form-item label="性别" name="sex" :rules="rules.sex" class="custom-form-item">
        <a-select v-model:value="formState.sex" placeholder="请选择性别" class="custom-select">
          <a-select-option value="男" class="custom-select-option">男</a-select-option>
          <a-select-option value="女" class="custom-select-option">女</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="姓名" name="name" :rules="[{ required: true, message: '请输入姓名' }]" class="custom-form-item">
        <a-input v-model:value="formState.name" placeholder="请输入姓名" class="custom-input" />
      </a-form-item>
      <a-form-item label="学院" name="college" :rules="[{ required: true, message: '请输入学院名称' }]" class="custom-form-item">
        <college-selector v-model="formState.college" placeholder="请选择指导教师所在学院" class="custom-college-selector" />
      </a-form-item>
      <a-form-item ref="sClass" label="班级" name="sClass" :labelCol="{ offset: 1 }">
        <class-selector v-model="formState.sClass" />
      </a-form-item>
      <a-form-item label="学号/工号" name="number" :rules="[{ required: true, message: '请输入学号或工号' }]"
        class="custom-form-item">
        <a-input v-model:value="formState.number" placeholder="请输入学号或工号" class="custom-input" />
      </a-form-item>
      <a-form-item label="邮箱" name="email"
        :rules="[{ required: true, message: '请输入邮箱地址' }, { type: 'email', message: '请输入有效的邮箱地址' }]"
        class="custom-form-item">
        <a-input v-model:value="formState.email" placeholder="请输入邮箱地址" class="custom-input" />
      </a-form-item>
      <a-form-item label="电话" name="phone"
        :rules="[{ required: true, message: '请输入电话号码' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的电话号码' }]"
        class="custom-form-item">
        <a-input v-model:value="formState.phone" placeholder="请输入电话号码" class="custom-input" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 查看我的所有团队 -->
  <a-modal v-model:visible="allTeamVisible" title="查看所有比赛" width="700px" :footer="null" class="custom-allRace">
    <a-empty v-if="!currentAllTeam.length" description="暂无团队信息" />

    <div v-else class="teams-list">
      <a-row :gutter="16">
        <a-col v-for="team in currentAllTeam" :key="team.id" :xs="24" :sm="12" :md="8" :lg="8">
          <div class="team-card">
            <div class="team-header">
              <div class="team-name">{{ team.name }}</div>
              <a-tag color="blue">{{ team.status }}</a-tag>
            </div>
            <div class="team-content">
              <p><user-outlined /> 负责人：{{ team.leaderName }}</p>
              <p><team-outlined /> 成员数：{{ team.memberCount }}</p>
              <p><trophy-outlined /> 参赛项目：{{ team.project }}</p>
            </div>
            <div class="button" style="display: flex;justify-content: space-evenly;flex-direction: row">
              <div class="team-footer">
                <a-button type="primary" size="small"
                  :style="{ backgroundColor: 'orange', borderColor: 'orange', color: 'black' }"
                  @click="handleRecruitClick(team)">招募</a-button>
              </div>
              <div class="team-footer">
                <a-button type="primary" size="small" @click="viewTeamDetail(team)">查看详情</a-button>
              </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
  </a-modal>


  <!-- //查看团队详情 -->
  <!-- <a-modal v-model:visible="findOutVisible" title="查看团队详情" @ok="TeamDetailOk" width="700px" class="custom-modal">
    <a-form ref="teamDetail" :model="currentTeamDetail" :rules="rules" layout="vertical">
      <a-form-item label="团队名称" name="name" :rules="[{ required: true, message: '请输入团队名称' }]">
        <a-input v-model:value="currentTeamDetail.name" placeholder="请输入团队名称" />
      </a-form-item>
      <a-form-item label="负责人" name="leaderName" required>
        <span class="value">{{ user.userInfo.name }}</span>
      </a-form-item>
      <a-form-item label="负责人手机号" name="phone" required>
        <span class="value">{{ user.userInfo.phone }}</span>
      </a-form-item>
      <a-form-item label="负责人邮箱" name="phone" required>
        <span class="value">{{ user.userInfo.email }}</span>
      </a-form-item>
      <a-form-item label="负责人学号" name="phone" required>
        <span class="value">{{ user.userInfo.number }}</span>
      </a-form-item>
      <a-form-item label="比赛名称" name="raceName" :rules="[{ required: true, message: '请输入比赛名称' }]">
        <a-input v-model:value="currentTeamDetail.raceName" placeholder="请输入比赛名称" />
      </a-form-item>
      <a-form-item label="比赛开始时间" name="start" :rules="[{ required: true, message: '请选择比赛开始时间' }]">
        <a-date-picker v-model:value="currentTeamDetail.start" placeholder="请选择比赛开始时间" />
      </a-form-item>
      <a-form-item label="比赛结束时间" name="end" :rules="[{ required: true, message: '请选择比赛结束时间' }]">
        <a-date-picker v-model:value="currentTeamDetail.end" placeholder="请选择比赛结束时间" />
      </a-form-item>
      <a-form-item label="所属学院" name="t1College" :rules="[{ required: true, message: '请输入所属学院' }]">
        <a-input v-model:value="currentTeamDetail.t1College" placeholder="请输入所属学院" />
      </a-form-item>
      <a-form-item label="指导教师" name="teacher1" :rules="[{ required: true, message: '请输入指导教师' }]">
        <a-input v-model:value="currentTeamDetail.teacher1" placeholder="请输入指导教师" />
      </a-form-item>
      <a-form-item label="团队描述" name="description" :rules="[{ required: false, message: '请输入团队描述' }]">
        <a-textarea v-model:value="currentTeamDetail.description" placeholder="请输入团队描述" :rows="4" />
      </a-form-item>
    </a-form>
  </a-modal> -->

  <!-- 发布招募弹窗 -->
  <a-modal v-model:visible="recruitModalVisible" title="招募要求" @ok="handleRecruitPop" @cancel="() => request.value = ''"
    class="recruit-modal">
    <a-form layout="vertical">
      <a-form-item>
        <a-textarea v-model:value="request" placeholder="请输入发布要求" rows="4" />
      </a-form-item>
    </a-form>
  </a-modal>


  <!-- //查看我的所有比赛 -->
  <a-modal v-model:visible="allRaceVisible" title="查看所有比赛" width="700px" :footer="null" class="custom-allRace">
    <a-empty v-if="!currentAllRace.length" description="暂无参赛记录" />

    <div v-else class="competition-list">
      <div v-for="race in currentAllRace" :key="race.id" class="competition-item">
        <a-tag :color="getRaceStatusColor(race.status)" class="competition-status">
          {{ getRaceStatusText(race.status) }}
        </a-tag>

        <div class="competition-info">
          <div class="competition-name">{{ race.name }}</div>
          <div class="competition-date">
            <calendar-outlined /> {{ race.raceStart }} 至 {{ race.raceEnd }}
          </div>
        </div>

        <div class="competition-actions">
          <a-button type="primary" size="small" @click="viewRaceDetail(race)">
            查看详情
          </a-button>
        </div>
      </div>
    </div>
  </a-modal>

  <!-- 查看我的比赛详情 -->
  <a-modal v-model:visible="raceDetailVisible" title="查看比赛详情" width="700px" :footer="null" class="custom-modal">
    <div class="info-item">
      <span class="label">比赛名称：</span>
      <span class="value">{{ currentRaceDetail.raceDetail.raceName }}</span>
    </div>
    <div class="info-item">
      <span class="label">比赛开始时间：</span>
      <span class="value">{{ currentRaceDetail.raceStart }}</span>
    </div>
    <div class="info-item">
      <span class="label">比赛结束时间：</span>
      <span class="value">{{ currentRaceDetail.raceEnd }}</span>
    </div>
    <div class="info-item">
      <span class="label">比赛类型：</span>
      <span class="value">
        {{ currentRaceDetail.raceType === 0 ? '创新创业类比赛' :
          currentRaceDetail.raceType === 1 ? '蓝桥杯' :
            currentRaceDetail.raceType === 2 ? '第二课堂' : '未知类型' }}
      </span>
    </div>
    <div class="info-item">
      <span class="label">比赛状态：</span>
      <span class="value">
        {{ currentRaceDetail.status === 0 ? '未开始' :
          currentRaceDetail.status === 1 ? '进行中' :
            currentRaceDetail.status === 2 ? '已结束' : '未知状态' }}
      </span>
    </div>
    <div class="info-item">
      <span class="label">报名开始时间：</span>
      <span class="value">{{ currentRaceDetail.joinStart }}</span>
    </div>
    <div class="info-item">
      <span class="label">报名结束时间：</span>
      <span class="value">{{ currentRaceDetail.joinEnd }}</span>
    </div>
    <div class="info-item">
      <span class="label">是否已报名：</span>
      <span class="value">{{ currentRaceDetail.isJoin === 1 ? '已报名' : '未报名' }}</span>
    </div>
    <div class="info-item">
      <span class="label">是否预报名：</span>
      <span class="value">{{ currentRaceDetail.isPreJoin === 1 ? '已预报名' : '未预报名' }}</span>
    </div>

    <div class="info-item">
      <span class="label">比赛负责人姓名：</span>
      <span class="value">{{ currentRaceDetail.raceDetail.name }}</span>
    </div>
    <div class="info-item">
      <span class="label">负责人电话：</span>
      <span class="value">{{ currentRaceDetail.raceDetail.phone }}</span>
    </div>
    <div class="info-item">
      <span class="label">负责人邮箱：</span>
      <span class="value">{{ currentRaceDetail.raceDetail.email }}</span>
    </div>
    <div class="info-item">
      <span class="label">比赛说明材料 URL：</span>
      <a :href="currentRaceDetail.raceDetail.descUrl" target="_blank">
        点击查看比赛说明材料
      </a>
    </div>
    <div class="info-item">
      <span class="label">比赛群二维码 URL：</span>
      <a :href="currentRaceDetail.raceDetail.groupUrl" target="_blank">
        点击查看比赛群二维码
      </a>
    </div>
  </a-modal>






</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useUserStore } from "@/store/user";
import { updateUserInfo, get_title, getCollegeMajor, getSex, getTeamDetail, getAllTeam, getUserTeams, updateUserTeams, race_detail, getUserAward } from "@/apis";
import { message, Modal } from "ant-design-vue";
import { handleTree } from "@/utils";
import {
  EditOutlined, TeamOutlined, TrophyOutlined, CrownOutlined,
  MailOutlined, PhoneOutlined, CalendarOutlined,
  ClockCircleOutlined, BankOutlined, CameraOutlined, NotificationOutlined,
  FileOutlined, UserOutlined, IdcardOutlined
} from '@ant-design/icons-vue';
import CollegeSelector from '@/components/CollegeSelector.vue';

const user = useUserStore();
import { useRouter } from 'vue-router';

const router = useRouter();

const toLogin = () => {
  const router = useRouter();
  router.push({ path: "/login" });
};
const loading = ref(false);
const formRef = ref();
const editModalVisible = ref(false);
const titleList = ref([]);
const sexData = ref([]);
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const collegeList = ref([]);
const collegeTreeList = ref([]);
const formState = ref({
  name: "",//姓名
  sex: user.userInfo?.sex || null,
  email: "",//邮箱
  phone: "",//电话
  major: "",//专业
  number: "",//学号
  title: "",//标题
  college: "",//学院
  description: "",//描述
  collegeList: [],//学院列表
  majorList: [],//专业列表
});
const rules = {
  name: [
    {
      required: true,
      message: "请输入姓名",
      trigger: "change",
    },
  ],
  sex: [
    {
      required: true,
      message: "请输入性别",
      trigger: "change",
    },
  ],
};

// 用户统计数据
const userStats = reactive({
  raceCount: 0,
  teamCount: 0,
  awardCount: 0
});

// 用户比赛和通知数据
const notifications = ref([]);
const userTeams = ref([]);

//学院
function handleChangeCollege(data) {
  console.log(data);
  formState.value.college = data[0];
  if (data.length > 1) {
    formState.value.major = data[1];
  }
}
function handleChangeMajor(data) {
  console.log(data);
  // formState.value.major = data[data.length - 1];
  formState.value.major = value;
}
const filterOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      //性别
      let genderValue = formState.value.sex === "男" ? 1 : 2;
      formState.value.sex = genderValue;
      loading.value = true;
      console.log("values", formState.value);
      updateUserInfo(formState.value)
        .then((res) => {
          loading.value = false;
          // user.setUser();
          message.success("更新成功");
        })
        .catch((error) => {
          loading.value = false;
        });
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const resetForm = () => {
  formRef.value.resetFields();
};


//性别
const getGenderText = (genderNum) => {
  return genderNum === 1 ? '男' : genderNum === 2 ? '女' : '未设置性别';
};


function getTitleList() {
  get_title().then((res) => {
    titleList.value = res.rows;
  });
}
function getCollegeMajorList() {
  getCollegeMajor().then((res) => {
    collegeList.value = res.data;
    collegeTreeList.value = handleTree(
      collegeList.value,
      "id",
      "college",
      "children"
    );
  });
}
function init() {
  if (!user.userInfo) {
    return;
  }
  formState.value.name = user.userInfo.name;
  formState.value.sex = user.userInfo.sex;
  formState.value.email = user.userInfo.email;
  formState.value.phone = user.userInfo.phone;
  formState.value.major = user.userInfo.major;
  formState.value.number = user.userInfo.number;
  formState.value.title =
    user.userInfo.title !== null ? user.userInfo.title + "" : null;
  formState.value.college = user.userInfo.college;
  formState.value.description = user.userInfo.description;
  formState.value.collegeList = [];
  formState.value.majorList = [];
  setTimeout(() => {
    if (formState.value.college !== null) {
      formState.value.collegeList.push(formState.value.college);
    }
    if (formState.value.major !== null) {
      formState.value.collegeList.push(formState.value.major);
    }
  }, 300);
}
function getSexList() {
  getSex().then((res) => {
    sexData.value = res.rows;
  });
}

// 初始化数据
onMounted(() => {

  getTitleList();
  getCollegeMajorList();
  getSexList();
  init();

  // 这里可以添加获取用户统计、比赛和通知的API调用
  // 获取示例数据
  fetchUserStats();
  fetchNotifications();
  fetchUserTeams();
  viewAllRaces();
  viewMyTeams();
  viewAllAward();
});

// 获取用户统计数据
function fetchUserStats() {
  // 这里应该是API调用，暂时使用模拟数据
  userStats.raceCount = 5;
  userStats.teamCount = 3;
  userStats.awardCount = 2;
}

// 获取通知数据
function fetchNotifications() {
  // 这里应该是API调用，暂时使用模拟数据
  notifications.value = [
    {
      id: 1,
      title: '系统通知：账号信息已更新',
      content: '您的个人资料已成功更新，请查看最新信息。',
      createTime: '2023-08-15 14:30',
      type: 'system',
      isUnread: true
    },
    {
      id: 2,
      title: '比赛提醒：作品提交截止日期临近',
      content: '2023年全国大学生创新创业大赛作品提交截止日期还有3天。',
      createTime: '2023-08-12 09:15',
      type: 'competition',
      isUnread: false
    }
  ];
}

// 获取用户团队数据
function fetchUserTeams() {
  // 这里应该是API调用，暂时使用模拟数据
  userTeams.value = [
    {
      id: 1,
      name: '创新先锋队',
      status: '进行中',
      leaderName: '张三',
      memberCount: 5,
      project: '智能家居系统'
    },
    {
      id: 2,
      name: '数据科学小组',
      status: '已完成',
      leaderName: '李四',
      memberCount: 4,
      project: '数据分析平台'
    }
  ];
}

// 工具函数
function getSexLabel(sex) {
  const sexItem = sexData.value.find(item => item.dictValue == sex);
  return sexItem ? sexItem.dictLabel : '未设置';
}

function getTitleLabel(title) {
  const titleItem = titleList.value.find(item => item.dictValue == title);
  return titleItem ? titleItem.dictLabel : null;
}

function getRaceStatusText(status) {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  };
  return statusMap[status] || '未知状态';
}

function getRaceStatusColor(status) {
  const colorMap = {
    0: 'orange', // 未开始，用橙色表示
    1: 'green', // 进行中，用绿色表示
    2: 'gray' // 已结束，用灰色表示
  };
  return colorMap[status] || 'default';
}

function getNotificationColor(type) {
  const colorMap = {
    'system': '#1890ff',
    'competition': '#52c41a',
    'document': '#faad14'
  };
  return colorMap[type] || '#1890ff';
}

// 事件处理函数
function showEditModal() {
  editModalVisible.value = true;
}

function handleEditOk() {
  formRef.value.validate().then(() => {
    onSubmit();
    editModalVisible.value = false;
  });
}


//所有比赛
const currentAllRace = ref([]);
const allRaceVisible = ref(false);
const raceCount = ref(0);

const viewAllRaces = async () => {
  const res = await getAllTeam(user.userInfo?.id);
  console.log(res);
  currentAllRace.value = res.data;
  console.log("所有比赛", currentAllRace.value);
  raceCount.value = currentAllRace.value.length;
  console.log(raceCount);
};

const toggleVisibility = () => {
  allRaceVisible.value = true; // 设置值为 true
};

//查看比赛详情
const currentRaceDetail = ref({
  raceName: '', // 比赛名称
  raceStart: '', // 比赛开始时间
  raceEnd: '', // 比赛结束时间
  raceType: 0, // 比赛类型，0: 创新创业类比赛, 1: 蓝桥杯, 2: 第二课堂
  status: 0, // 比赛状态，0: 未开始, 1: 进行中, 2: 已结束
  joinStart: '', // 报名开始时间
  joinEnd: '', // 报名结束时间
  isJoin: 0, // 是否已报名，1: 已报名, 0: 未报名
  isPreJoin: 0, // 是否预报名，1: 已预报名, 0: 未预报名
  name: '', // 比赛负责人姓名
  phone: '', // 负责人电话
  email: '', // 负责人邮箱
  descUrl: '', // 比赛说明材料 URL
  groupUrl: '' // 比赛群二维码 URL
});
const raceDetailVisible = ref(false);

const viewRaceDetail = async (race) => {
  const res = await race_detail(race.id);
  currentRaceDetail.value = res.data;
  console.log(currentRaceDetail.value);
  raceDetailVisible.value = true;
}


function viewAllNotifications() {
  // 跳转到所有通知页面
}


//我的团队全部
const currentAllTeam = ref([]);
const allTeamVisible = ref(false);
const currentPage = ref(1);
const total = ref(0);
const teamCount = ref(0);

const viewMyTeams = async () => {
  const pageNum = parseInt(currentPage.value, 10)
  const params = {
    pageNum,
    pageSize: 20,
    userId: user.userInfo?.id
  };
  const res = await getUserTeams(params);

  if (res && res.code === 200) {
    currentAllTeam.value = res.rows;
    total.value = res.total;
    // console.log("所有团队", currentAllTeam.value);
    // console.log("所有团队", currentAllTeam.value);
    console.log("所有团队", currentAllTeam.value);
    teamCount.value = currentAllTeam.value.length;
  }

};

const MyTeamesVisibility = () => {
  allTeamVisible.value = true;
}

// 比赛类型数据
const raceTypeList = ref([
  { dictValue: 0, dictLabel: "创新创业类比赛" },
  { dictValue: 1, dictLabel: "蓝桥杯" },
  { dictValue: 2, dictLabel: "第二课堂" },
]);
//团队状态
const getProjectType = (typeId) => {
  // console.log("raceTypeList", raceTypeList.value);
  // console.log("typeId", typeId);
  const type = raceTypeList.value.find(
    (item) => Number(item.dictValue) === typeId
  );
  // console.log("type", type);
  return type ? type.dictLabel : "未知类型";
};



const getRaceTypeColor = (typeId) => {
  switch (typeId) {
    case 0:
      return "orange"; // 创新创业类比赛使用橙色
    case 1:
      return "blue"; // 蓝桥杯使用蓝色
    case 2:
      return "green"; // 第二课堂使用绿色
    default:
      return "gray"; // 默认灰色
  }
};

// 查看团队详情
const currentTeamDetail = ref({
  name: '',
  leaderName: '',
  phone: '',
  email: '',
  number: '',
  raceName: '',
  start: '',
  end: '',
  t1College: '',
  teacher1: '',
  description: ''
});
const findOutVisible = ref(false);
const teamDetail = ref(null);

// const viewTeamDetail = async (team) => {
//   const res = await getTeamDetail(team.id);
//   currentTeamDetail.value = res.data;
//   console.log(currentTeamDetail.value);
//   findOutVisible.value = true;
// };

const viewTeamDetail = (team) => {
  if (!team.id) {
    message.error('团队ID不存在');
    return;
  }
  router.push({ 
    path: "/user/test",
    query: { teamId: team.id }
  });
};

const onTeamDetailSubmit = () => {
  currentTeamDetail.value
    .validate()
    .then(() => {
      console.log("Form data:", currentTeamDetail.value);
      console.log(team.id);
      updateUserTeams(team.id, currentTeamDetail.value).then(() => {
        // 更新成功后的操作
        console.log("Team updated successfully");
        findOutVisible.value = false; // 关闭模态框
        // 如果需要，可以在这里刷新团队列表
        // fetchTeamList();
      })
    })
    .catch((error) => {
      console.error("Validation error:", error);
    });
};

function TeamDetailOk() {
  teamDetail.validate().then(() => {
    onTeamDetailSubmit();
  }
  )
}


const recruitModalVisible = ref(false); // 控制招募弹窗的显示
const request = ref(''); // 发布要求
const currentTeam = ref(null);//团队

//招募
const handleRecruitClick = (team) => {
  recruitModalVisible.value = true;
  currentTeam.value = team;
};


const handleRecruitPop = async () => {
  const updatedData = {
    action: 'recruit',
    isPublish: "Y",
    requirements: request.value
  };
  const res = await updateUserTeams({ teamId: currentTeam.value.id }, updatedData);
  if (res && res.code === 200) {
    message.success('招募成功');
    recruitModalVisible.value = false;
    request.value = '';
  } else {
    message.error('招募失败，请稍后再试');
  }
};

//查询获取的奖项
const currentAllAward = ref([]);
const awardCount = ref(0);

const viewAllAward = async () => {
  const res = await getUserAward(user.userInfo?.id);
  currentAllAward.value = res.data;
  awardCount.value = currentAllAward.value.length;
  console.log("奖项", awardCount);
}




function beforeAvatarUpload(file) {
  // 处理头像上传逻辑
  return false;
}

watch(
  () => user.userInfo,
  () => {
    init();
  }
);
</script>

<style lang="less" scoped>
.user-center-container {
  min-height: 100vh;
  background-color: #f0f2f5;
  padding-bottom: 40px;
  margin-top: var(--container-header-margin-top, 60px);
  /* 使用变量或提供一个默认值 */
}

.user-center-layout {
  // max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
}

// 侧边栏列样式
.sidebar-col {
  display: flex;
  flex-direction: column;
}

// 侧边栏容器样式
.sidebar-container {
  position: sticky;
  top: calc(var(--container-header-margin-top, 60px) + 20px);
  /* 头部高度 + 额外边距 */
  height: fit-content;
}

// 内容列样式
.content-col {
  display: flex;
  flex-direction: column;
}

// 个人信息卡片
.user-profile-card {
  background: linear-gradient(135deg, #654ea3 0%, #da98b4 100%);
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  color: white;
  padding: 30px 20px;
  text-align: center;
  margin-bottom: 24px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  }

  .avatar-container {
    position: relative;
    display: inline-block;
    margin-bottom: 15px;

    .avatar-upload {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }

  .user-sex {
    margin: 10px 0;
  }

  .user-name {
    font-size: 22px;
    margin: 10px 0;
    font-weight: 600;
  }

  .user-tags {
    margin-bottom: 20px;
  }

  .user-info-item {
    text-align: left;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 12px;
    padding: 0 8px;

    .anticon {
      font-size: 16px;
    }
  }

  .action-buttons {
    margin-top: 20px;
  }
}

// 左侧底部统计卡片
.sidebar-stats-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  }

  h3 {
    margin: 0 0 15px 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .stats-row {
    display: flex;
    flex-direction: column;
    gap: 15px;

    .stat-item {
      display: flex;
      align-items: center;
      gap: 12px;

      .anticon {
        font-size: 24px;
        color: #1890ff;
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 18px;
          font-weight: 600;
          color: #333;
        }

        .stat-label {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

// 右侧内容区样式
.main-content {
  .content-card {
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
    }

    :deep(.ant-card-head) {
      font-weight: 600;
      font-size: 18px;
    }
  }

  // 比赛卡片
  .competitions-card {
    .competition-list {
      .competition-item {
        display: flex;
        align-items: center;
        padding: 16px;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          background-color: #f9f9f9;
        }

        .competition-status {
          margin-right: 15px;
        }

        .competition-info {
          flex: 1;

          .competition-name {
            font-weight: 500;
            margin-bottom: 5px;
          }

          .competition-date {
            color: #888;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
          }
        }
      }
    }
  }

  // 通知卡片
  .notifications-card {
    .notification-list {
      :deep(.ant-list-item) {
        padding: 12px;
        transition: background-color 0.3s;

        &:hover {
          background-color: #f9f9f9;
        }

        .notification-title {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .notification-desc {
          color: #666;

          .notification-time {
            font-size: 12px;
            color: #999;
            margin-top: 6px;
            display: flex;
            align-items: center;
            gap: 5px;
          }
        }
      }
    }
  }

  // 团队卡片
  .teams-card {
    .teams-list {
      .team-card {
        height: 200px;
        background-color: white;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        padding: 16px;
        margin-bottom: 16px;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
        }

        .team-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .team-name {
            font-weight: 600;
            font-size: 16px;
          }
        }

        .team-content {
          p {
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
          }
        }

        .team-footer {
          margin-top: 12px;
          text-align: right;
        }
      }
    }
  }
}


.custom-modal {
  .modal-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .info-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 10px 0;
    border-bottom: 1px solid #e8e8e8;

    .info-item:last-child {
      border-bottom: none;
    }

    .label {
      font-weight: bold;
      margin-right: 16px;
      color: #333;
    }

    .value {
      flex: 1;
      color: #666;
    }
  }

}

.custom-allRace {
  .competition-list {
    .competition-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f9f9f9;
      }

      .competition-status {
        margin-right: 15px;
      }

      .competition-info {
        flex: 1;

        .competition-name {
          font-weight: 500;
          margin-bottom: 5px;
        }

        .competition-date {
          color: #888;
          font-size: 12px;
          display: flex;
          align-items: center;
          gap: 5px;
        }
      }
    }
  }

}

.custom-edit-modal {
  .ant-modal-content {
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
    }

    .ant-modal-header {
      background-color: #f0f2f5;
      border-bottom: none;
      padding: 16px;
      border-radius: 12px 12px 0 0;

      .ant-modal-title {
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }
    }

    .ant-modal-body {
      padding: 24px;
      background-color: #ffffff;
      border-radius: 0 0 12px 12px;
    }
  }
}



// 响应式调整
@media (max-width: 768px) {
  .sidebar-container {
    position: static;
    /* 移动端不使用sticky定位 */
    margin-bottom: 24px;
  }

  .user-center-container {
    margin-top: var(--container-header-margin-top-mobile, 50px);
    /* 移动端头部可能有不同高度 */
  }
}
</style>